package com.example.ruiji.filter;




import com.alibaba.fastjson.JSON;
import com.example.ruiji.common.BaseContext;
import com.example.ruiji.pojo.R;
import com.sun.net.httpserver.HttpExchange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.LogRecord;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)  servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //1.获取请求url
        String url=request.getRequestURI();
        //2.定义不需要拦截的路径
        //1.所有静态资源  包括登录验证 包括退出
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"


        };
        ///3.请求url中是否需要被处理 --我们需要一个可以判断url是否有其中关键词的
        boolean check=check(urls,url);
        if(check)
        {
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //4.有敏感操作的路径 --判断seeion
        if(request.getSession().getAttribute("employee")!=null)
        {
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        //4.有敏感操作的路径 --判断seeion
        if(request.getSession().getAttribute("user")!=null)
        {
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //前端接受响应对数据进行判断
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }
    //进行路径匹配的函数
    public  boolean check(String[] urls, String url)
    {
        for(String urll:urls)
        {
            boolean match=PATH_MATCHER.match(urll,url);
            if(match)
            {
                return  true;
            }
        }

        return false;
    }

}
